<?php
class Wenda_Model_Answer extends Life_Model_Abstract
{

    public function findById($id)
    {
        return Life_Core::getTable('Answer')->findById($id);
    }

    /**
     * Get answers by query id
     *
     * @param int $id Query id
     * @return Zend_Db_Table_Rowset
     */
    public function getAnswers($id)
    {
        return Life_Core::getTable('Answer')->getAnswers($id);
    }

    public function save($data, $validator= null)
    {
        if (null === $validator) {
            $validator = 'Answer';
        }

        $validator = Life_Core::getForm('query' . ucfirst($validator));
        if (!$validator->isValid($data)) {
            return false;
        }

        if (array_key_exists('id', $data)) {
            $row = $this->findById($data['id']);
        } else {
            $row = null;
            $data['created_at'] = date('Y-m-d H:i:s', time());
        }
        $this->setDefault($data);

        return Life_Core::getTable('Answer')->saveRow($data, $row);
    }

    public function setDefault(&$data)
    {
        $request = new Zend_Controller_Request_Http();

        $auth   = Life_Core::getService('authentication')->getAuth();
        $user = $auth->hasIdentity() ? $auth->getStorage()->read() : array('id'=>1);

        $data['user_id']    = $user['id'];
        $data['updated_at'] = date('Y-m-d H:i:s', time());
        $data['status']     = 'A';
        $data['ip_address'] = $request->getClientIp();
    }

}